package net.adetech.dcweb.core.dc.service.impl;

import net.adetech.dcweb.core.dc.entity.DcAuditComment;
import net.adetech.dcweb.core.dc.service.IDcAuditCommentService;
import net.adetech.utils.condition.ConditionEntity;
import net.adetech.utils.condition.ConditionTools;
import net.adetech.utils.condition.SQLEntity;
import net.adetech.utils.spring.PageBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by sunfeihu on 2016/10/20.
 */
@Service
public class DcAuditCommentServiceImpl implements IDcAuditCommentService {

    private final Logger logger = LoggerFactory.getLogger(DcAuditCommentServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public DcAuditComment save(DcAuditComment entity) {
        final String sql = " insert into dc_audit_comment (uuid,add_user,add_date,add_ip,add_info,update_user,update_date,update_ip,update_info,info_id,audit_date,content,auditer,audit_type,remark,is_delete) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final DcAuditComment finalEntity = entity;
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1, finalEntity.getUuid());
                ps.setObject(2, finalEntity.getAddUser());
                if (null != finalEntity.getAddDate()) {
                    ps.setObject(3, new Timestamp(finalEntity.getAddDate().getTime()));
                } else {
                    ps.setObject(3, null);
                }
                ps.setObject(4, finalEntity.getAddIp());
                ps.setObject(5, finalEntity.getAddInfo());
                ps.setObject(6, finalEntity.getUpdateUser());
                if (null != finalEntity.getUpdateDate()) {
                    ps.setObject(7, new Timestamp(finalEntity.getUpdateDate().getTime()));
                } else {
                    ps.setObject(7, null);
                }
                ps.setObject(8, finalEntity.getUpdateIp());
                ps.setObject(9, finalEntity.getUpdateInfo());
                ps.setObject(10, finalEntity.getInfoId());
                if (null != finalEntity.getAuditDate()) {
                    ps.setObject(11, new Timestamp(finalEntity.getAuditDate().getTime()));
                } else {
                    ps.setObject(11, null);
                }
                ps.setObject(12, finalEntity.getContent());
                ps.setObject(13, finalEntity.getAuditer());
                ps.setObject(14, finalEntity.getAuditType());
                ps.setObject(15, finalEntity.getRemark());
                ps.setObject(16, finalEntity.getIsDelete());
                return ps;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        return this.find(id);
    }

    @Override
    public int delete(Long id) {
        final String sql = " update dc_audit_comment set is_delete = 1 where id = ? ";
        return jdbcTemplate.update(sql, new Object[]{
                id
        });
    }

    @Override
    public int update(DcAuditComment entity) {
        final String sql = " update dc_audit_comment set add_info=?,update_info=?,info_id=?,audit_date=?,content=?,auditer=?,audit_type=?,remark=? where id = ?";
        return jdbcTemplate.update(sql, new Object[]{
                entity.getAddInfo(),
                entity.getUpdateInfo(),
                entity.getInfoId(),
                entity.getAuditDate(),
                entity.getContent(),
                entity.getAuditer(),
                entity.getAuditType(),
                entity.getRemark(),
                entity.getId()
        });
    }

    @Override
    public DcAuditComment find(Long id) {
        final String sql = " select * from dc_audit_comment where id = ? and is_delete = 0 ";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{id}, new DcAuditCommentRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void save(List<DcAuditComment> list) {
        if (null != list && list.size() > 0) {
            final String sql = " insert into dc_audit_comment (uuid,add_user,add_date,add_ip,add_info,update_user,update_date,update_ip,update_info,info_id,audit_date,content,auditer,audit_type,remark,is_delete) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            List
                    <Object[]> params = new ArrayList
                    <Object[]>();
            Object[] objArr = null;
            DcAuditComment entity = null;
            for (int i = 0; i < list.size(); i++) {
                entity = list.get(i);
                objArr = new Object[16];
                objArr[0] = entity.getUuid();
                objArr[1] = entity.getAddUser();
                objArr[2] = entity.getAddDate();
                objArr[3] = entity.getAddIp();
                objArr[4] = entity.getAddInfo();
                objArr[5] = entity.getUpdateUser();
                objArr[6] = entity.getUpdateDate();
                objArr[7] = entity.getUpdateIp();
                objArr[8] = entity.getUpdateInfo();
                objArr[9] = entity.getInfoId();
                objArr[10] = entity.getAuditDate();
                objArr[11] = entity.getContent();
                objArr[12] = entity.getAuditer();
                objArr[13] = entity.getAuditType();
                objArr[14] = entity.getRemark();
                objArr[15] = entity.getIsDelete();
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public void delete(List
                               <Long> ids) {
        if (null != ids && ids.size() > 0) {
            final String sql = " update dc_audit_comment set is_delete = 1 where id = ? ";
            List
                    <Object
                            []> params = new ArrayList
                    <Object
                            []>();
            Object[] objArr = null;
            for (int i = 0; i < ids.size(); i++) {
                objArr = new Object[1];
                objArr[0] = ids.get(i);
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public void update(List<DcAuditComment> list) {
        if (null != list && list.size() > 0) {
            final String sql = " update dc_audit_comment set add_info=?,update_info=?,info_id=?,audit_date=?,content=?,auditer=?,audit_type=?,remark=? where id = ?";
            List
                    <Object
                            []> params = new ArrayList
                    <Object
                            []>();
            Object[] objArr = null;
            DcAuditComment entity = null;
            for (int i = 0; i < list.size(); i++) {
                entity = list.get(i);
                objArr = new Object[8];
                objArr[0] = entity.getAddInfo();
                objArr[1] = entity.getUpdateInfo();
                objArr[2] = entity.getInfoId();
                objArr[3] = entity.getAuditDate();
                objArr[4] = entity.getContent();
                objArr[5] = entity.getAuditer();
                objArr[6] = entity.getAuditType();
                objArr[7] = entity.getRemark();
                objArr[8] = entity.getId();
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public PageBean<DcAuditComment> page(int nowPage, int pageSize, ConditionEntity conditionEntity) {
        SQLEntity sqlEntity = ConditionTools.conditionEntities2SQL(conditionEntity);
        final String sql = " select * from dc_audit_comment where 1 = 1 and is_delete = 0 " + sqlEntity.getSql() + " order by " + sqlEntity.getOrder();
        return new PageBean<DcAuditComment>(sql, sqlEntity.getParams(), nowPage, pageSize,
                new DcAuditCommentRowerMapper(), jdbcTemplate);
    }

    @Override
    public List<DcAuditComment> getLog(int page) {

        final String sql = "  select * , (select real_name from common_adminuser where id = auditer) as realname from dc_audit_comment where is_delete = 0   ORDER BY audit_date desc limit " + page * 10 + ",10  ";

        try {
            return jdbcTemplate.query(sql, new Object[]{}, new DcAuditCommentRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }


    class DcAuditCommentRowerMapper implements RowMapper<DcAuditComment> {
        @Override
        public DcAuditComment mapRow(ResultSet rs, int rowNum) throws SQLException {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Set
                    <String> fieldSet = new HashSet
                    <String>();
            for (int i = 1; i <= columnCount; i++) {
                fieldSet.add(rsmd.getColumnName(i));
            }
            DcAuditComment entity = new DcAuditComment();
            if (fieldSet.contains("add_date") && null !=
                    rs.getObject("add_date")) {
                entity.setAddDate(new
                        java.util.Date(rs.getTimestamp("add_date").getTime()));
            }
            if (fieldSet.contains("update_info") && null !=
                    rs.getObject("update_info")) {
                entity.setUpdateInfo(rs.getString
                        ("update_info"));
            }
            if (fieldSet.contains("realname") && null !=
                    rs.getObject("realname")) {
                entity.setRealname(rs.getString
                        ("realname"));
            }
            if (fieldSet.contains("audit_date") && null !=
                    rs.getObject("audit_date")) {
                entity.setAuditDate(new
                        java.util.Date(rs.getTimestamp("audit_date").getTime()));
            }
            if (fieldSet.contains("remark") && null !=
                    rs.getObject("remark")) {
                entity.setRemark(rs.getString
                        ("remark"));
            }
            if (fieldSet.contains("update_ip") && null !=
                    rs.getObject("update_ip")) {
                entity.setUpdateIp(rs.getString
                        ("update_ip"));
            }
            if (fieldSet.contains("uuid") && null !=
                    rs.getObject("uuid")) {
                entity.setUuid(rs.getString
                        ("uuid"));
            }
            if (fieldSet.contains("update_date") && null !=
                    rs.getObject("update_date")) {
                entity.setUpdateDate(new
                        java.util.Date(rs.getTimestamp("update_date").getTime()));
            }
            if (fieldSet.contains("content") && null !=
                    rs.getObject("content")) {
                entity.setContent(rs.getString
                        ("content"));
            }
            if (fieldSet.contains("is_delete") && null !=
                    rs.getObject("is_delete")) {
                entity.setIsDelete(rs.getBoolean
                        ("is_delete"));
            }
            if (fieldSet.contains("add_ip") && null !=
                    rs.getObject("add_ip")) {
                entity.setAddIp(rs.getString
                        ("add_ip"));
            }
            if (fieldSet.contains("update_user") && null !=
                    rs.getObject("update_user")) {
                entity.setUpdateUser(rs.getString
                        ("update_user"));
            }
            if (fieldSet.contains("info_id") && null !=
                    rs.getObject("info_id")) {
                entity.setInfoId(rs.getLong
                        ("info_id"));
            }
            if (fieldSet.contains("id") && null !=
                    rs.getObject("id")) {
                entity.setId(rs.getLong
                        ("id"));
            }
            if (fieldSet.contains("add_info") && null !=
                    rs.getObject("add_info")) {
                entity.setAddInfo(rs.getString
                        ("add_info"));
            }
            if (fieldSet.contains("add_user") && null !=
                    rs.getObject("add_user")) {
                entity.setAddUser(rs.getString
                        ("add_user"));
            }
            if (fieldSet.contains("auditer") && null !=
                    rs.getObject("auditer")) {
                entity.setAuditer(rs.getLong
                        ("auditer"));
            }
            if (fieldSet.contains("audit_type") && null !=
                    rs.getObject("audit_type")) {
                entity.setAuditType(rs.getInt
                        ("audit_type"));
            }
            return entity;
        }
    }
}